package com.ehouse;

import java.util.HashMap;
import java.util.UUID;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.ehouse.connection.ConnectionService;
import com.ehouse.connection.ConnectionService.IConnectionResponseListener;
import com.ehouse.fragments.LightsSchedulesFragment;
import com.ehouse.models.Rule;
import com.ehouse.models.Settings;

public class ScheduleAddActivity extends FragmentActivity {
	public static final String LOG_TAG = "SCHEDULE_ADD";
	public static final boolean DEBUG = MainActivity.DEBUG;
	private int type;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		type = (int)getIntent().getIntExtra("type", 0);
		switch(type){
		case 2:{
			setTitle(R.string.name_add_irri_schedules);
			setContentView(R.layout.add_irri_schedule);
			TimePicker timePicker = (TimePicker)findViewById(R.id.timeAdd);
			timePicker.setIs24HourView(true);
			break;
		}
		case 1:{
			setTitle(R.string.name_add_temp_schedules);
			setContentView(R.layout.add_temp_schedule);
			break;
		}
		case 0:{
			setTitle(R.string.name_add_light_schedules);
			setContentView(R.layout.add_light_schedule);
			TimePicker timePicker = (TimePicker)findViewById(R.id.timeAdd);
			timePicker.setIs24HourView(true);
		}
		default:
			break;
		}
    }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_schedule_add, menu);
		return true;
	}
	
	private HashMap<String, Boolean> getLightStatus(){

    	
		FragmentManager fragmentManager = getSupportFragmentManager();
    	LightsSchedulesFragment lightScheduleFragment = (LightsSchedulesFragment)fragmentManager.findFragmentById(R.id.lights_fragment);
       
		return lightScheduleFragment.getLights();
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.menu_schedule_save:
			switch(type){
			case 2:{
				TimePicker timePicker = (TimePicker)findViewById(R.id.timeAdd);
				timePicker.setIs24HourView(true);
				String minutes = String.valueOf(timePicker.getCurrentMinute());
				minutes = "0" + minutes;
				String time = String.valueOf(timePicker.getCurrentHour()) + ":" + (minutes.substring((minutes.length()-2), minutes.length()));
				ToggleButton toggleButton =  (ToggleButton)findViewById(R.id.stateAdd);
				boolean state = toggleButton.isChecked();
				
				 String uniqueID = UUID.randomUUID().toString();
				
				//Add to db
				Rule rule = new Rule(uniqueID, time,  "", state);
				
				//Send to server
				if(!DEBUG)
				serviceRef.addIrrigationRule(rule, new IConnectionResponseListener() {
					
					public void responseReceived(Object data, boolean success) {
						if(success){
							serviceRef.loadRules("Irrigation", new IConnectionResponseListener() {
								
								public void responseReceived(Object data, boolean success) {
									if(success){
										setResult(type);
										finish();
										}
								}
							});
						}
						
					}
				});
				
				break;
			}
			case 1:{
				EditText temperatureView =  (EditText)findViewById(R.id.tempAdd);
				String temp = temperatureView.getText().toString();
				
				String uniqueID = UUID.randomUUID().toString();
				
				
				SharedPreferences sharedPrefs = PreferenceManager
						.getDefaultSharedPreferences(this);
				boolean fahrenheit = (sharedPrefs.getString(Settings.TEMP_UNIT, "0").equals("1"));
				
				if(fahrenheit){
					Double tempDouble = Double.parseDouble(temp);
					tempDouble = ((tempDouble- 32)/1.8);
					temp =  String.valueOf(tempDouble);
				}
				
				
				//Add to db
				Rule rule = new Rule(uniqueID, temp,  "", temp);

				//Send to server
				if(!DEBUG)
				serviceRef.addTemperatureRule(rule,new IConnectionResponseListener() {
					
					public void responseReceived(Object data, boolean success) {
						if(success){
							serviceRef.loadRules("Temperature", new IConnectionResponseListener() {
								
								public void responseReceived(Object data, boolean success) {
									if(success){
										setResult(type);
										finish();
									}
									}
							});
						}
						
					}
				});
				
				break;
			}
			case 0:{
				TimePicker timePicker = (TimePicker)findViewById(R.id.timeAdd);
				timePicker.setIs24HourView(true);
				String minutes = String.valueOf(timePicker.getCurrentMinute());
				minutes = "0" + minutes;
				String time = String.valueOf(timePicker.getCurrentHour()) + ":" + (minutes.substring((minutes.length()-2), minutes.length()));
				
				
				ToggleButton toggleButton =  (ToggleButton)findViewById(R.id.stateAdd);
				boolean state = toggleButton.isChecked();
				
				String uniqueID = UUID.randomUUID().toString();
				
				HashMap<String, Boolean> lightData = getLightStatus();
				lightData.put("VALUE", state);
				

				//Add to db
				Rule rule = new Rule(uniqueID, time,"", lightData);
				
				//Send to servers
				if(!DEBUG)
					serviceRef.addLightRule(rule,new IConnectionResponseListener() {
					
					public void responseReceived(Object data, boolean success) {
						if(success){
							serviceRef.loadRules("Lights", new IConnectionResponseListener() {
								
								public void responseReceived(Object data, boolean success) {
									if(success){
										setResult(type);
										finish();
										}
								}
							});
						}
						
					}
				});
				break;
			}
			default:
				break;
			}
			
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	
	 //Service connection
    public static ConnectionService serviceRef;
    
    
    private ServiceConnection mConnection = new ServiceConnection() {
     public void onServiceConnected(ComponentName className, 
                                    IBinder service) {
       // Called when the connection is made.
       serviceRef = ((ConnectionService.ConnectionBinder)service).getService();
       onBinding();
     }
     
     public void onServiceDisconnected(ComponentName className) {

       // Received when the service unexpectedly disconnects.
       serviceRef = null;
     }
    };
	
	public void onBinding() {
		final SharedPreferences sharedPrefs = PreferenceManager
				.getDefaultSharedPreferences(this);
		String ip = sharedPrefs.getString(Settings.IP, "");

		if (ip.length() > 0) {
			serviceRef.openConnection(ip, new IConnectionResponseListener() {

				public void responseReceived(Object data, boolean success) {
					if (!success){
						ScheduleAddActivity.this.runOnUiThread(new Runnable() {
						    public void run() {
						    	if(!DEBUG)
						    		startActivity(new Intent(ScheduleAddActivity.this, PreferencesActivity.class));
								Toast.makeText(ScheduleAddActivity.this,
								R.string.connection_error, Toast.LENGTH_LONG)
								.show();
						    }
						});

					}else{
						System.out.println("BINDED");
					}
				}
			});
		} else {
			startActivity(new Intent(this,
					PreferencesActivity.class));
		}
	}
	
	 @Override
	    public void onPause(){
	    	super.onPause();
	    	if(serviceRef != null){
	    		serviceRef.closeConnection();
	    		unbindService(mConnection);
	    	}
	    	serviceRef = null;
	    }
	 
	 @Override
	    public void onResume(){
	    	super.onResume();
	 
	        Intent bindIntent = new Intent(this, ConnectionService.class);
	        bindService(bindIntent, mConnection, Context.BIND_AUTO_CREATE);
	    }
	    

	}
